<template>
  <section class="component changeInfo">
    <el-form :model="dataForm" label-width="110px" :rules="rules" ref="dataForm">
      <el-form-item>
        <div>已选择{{this.selectionList.length}}案件</div>
      </el-form-item>
      <el-form-item label="归属机构：" prop="deptId">
        <el-cascader v-model="dataForm.deptId" :options="departmentData" @change="handleChange" :props="{value:'id',label:'deptName', checkStrictly: true }"></el-cascader>
      </el-form-item>
      <el-form-item label="归属人：" prop="applyId">
        <el-select placeholder="请选择" v-model="dataForm.applyId">
          <el-option v-for="{index,realName,id} in userList" :key="index" :label="realName" :value="id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <div class="operate-buttons">
      <el-button @click="emitClose">取消</el-button>
      <el-button @click="commit" :loading="loading">确定</el-button>
    </div>
  </section>
</template>
<script lang="ts">
import { Vue, Component, Prop, Emit } from 'vue-property-decorator'
import { Getter, State } from 'vuex-class'
import { UserService } from "~/services/management-service/user.service";
import { Dependencies } from "~/core/decorator";
import { CarManageService } from "~/services/domain-service/car-manage.service";

@Component({
  components: {}
})

export default class ChangeInfo extends Vue {
  @Dependencies(UserService)
  private userService: UserService;
  @Dependencies(CarManageService)
  private carManageService: CarManageService;
  @Prop() private selectionList
  @Getter private departmentData
  @State private departmentList
  private dataForm: any = {
    deptId: '',
    applyId: ''
  }
  private userList: any = []
  private rules: any = {
    deptId: { required: true, type: 'array', message: '请选择归属机构' },
    applyId: { required: true, message: '请选择归属人' }
  }
  private loading: boolean = false

  @Emit('close') private emitClose() {
    this.reset()
  }

  private handleChange(val) {
    this.dataForm.applyId = ''
    const obj = this.departmentList.find(v => v.id === val[val.length - 1])
    this.userService
      .getAllUsersList({ deptCode: obj.deptCode })
      .subscribe(data => {
        this.userList = data;
      });
  }

  private commit() {
    const from: any = this.$refs['dataForm']
    from.validate((valid) => {
      if (!valid) return
      const ids = this.selectionList.map(v => v.id)
      const deptId = this.dataForm.deptId[this.dataForm.deptId.length - 1]
      const applyId = this.dataForm.applyId
      this.carManageService.updateApplyUserInfo({ ids, deptId, applyId }).subscribe(data => {
        this.emitClose()
        this.loading = false
        if (!data) {
          this.$message.success("非归C结清案件不能变更归属人！");
        }
      }, error => { this.loading = false })
    })
  }

  private reset() {
    const from: any = this.$refs['dataForm']
    from.resetFields()
  }
}
</script>